package com.hsmpay.mobile.util.icc;

public final class DESKey {
    private byte[] partA;
    private byte[] partB;
    private byte[] partC;

    private int keyLength;

    public DESKey(byte[] key) {
        setKey(key);
    }

    public DESKey(String hexKey) {
        setKey(ByteUtil.hex2Bin(hexKey));
    }

    public DESKey(byte[] leftKey, byte[] rightKey) {
        setKey(leftKey, rightKey);
    }

    public void setKey(byte[] key) {
        if (key.length == 8) {
            partA = key;
            partB = key;
            partC = key;
            keyLength = 8;
        } else if (key.length == 16) {
            partA = new byte[8];
            partB = new byte[8];
            System.arraycopy(key, 0, partA, 0, 8);
            System.arraycopy(key, 8, partB, 0, 8);
            partC = partA;
            keyLength = 16;
        } else {
            throw new RuntimeException("Invalid Key Length");
        }
    }

    public void setKey(String hexKey) {
        setKey(ByteUtil.hex2Bin(hexKey));
    }

    public void setKey(byte[] leftKey, byte[] rightKey) {
        if (leftKey.length == 8 && rightKey.length == 8) {
            partA = leftKey;
            partB = rightKey;
            partC = leftKey;
            keyLength = 16;
        } else {
            throw new RuntimeException("Error Key Length");
        }
    }

    public byte[] getPartA() {
        return partA;
    }

    public void setPartA(byte[] partA) {
        this.partA = partA;
    }

    public byte[] getPartB() {
        return partB;
    }

    public void setPartB(byte[] partB) {
        this.partB = partB;
    }

    public byte[] getPartC() {
        return partC;
    }

    public void setPartC(byte[] partC) {
        this.partC = partC;
    }

    public int getKeyLength() {
        return keyLength;
    }

    public void setKeyLength(int keyLength) {
        this.keyLength = keyLength;
    }

    public byte[] getKey() {
        if (keyLength == 8) return partA;
        else if (keyLength == 16) {
            byte[] key = new byte[16];
            System.arraycopy(partA, 0, key, 0, 8);
            System.arraycopy(partB, 0, key, 8, 8);
            return key;
        } else return null;
    }
}
